<template>
  <div class="facility-management">
    <div class="management-header">
      <h2>设施设备管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设备编号、设备名称、位置"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="设备状态" style="width: 120px" clearable @change="handleSearch">
          <el-option label="正常" :value="1" />
          <el-option label="维修中" :value="2" />
          <el-option label="报废" :value="3" />
        </el-select>
        <el-button 
          v-if="userStore.canManageFacilities" 
          type="primary" 
          @click="handleAddNew">
          <el-icon><Plus /></el-icon>
          新增设备
        </el-button>
        <el-button type="success" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-item">
        <div class="stat-number">{{ statistics.totalCount }}</div>
        <div class="stat-label">总设备数</div>
      </div>
      <div class="stat-item normal">
        <div class="stat-number">{{ statistics.normalCount }}</div>
        <div class="stat-label">正常</div>
      </div>
      <div class="stat-item maintaining">
        <div class="stat-number">{{ statistics.maintainingCount }}</div>
        <div class="stat-label">维修中</div>
      </div>
      <div class="stat-item scrapped">
        <div class="stat-number">{{ statistics.scrappedCount }}</div>
        <div class="stat-label">报废</div>
      </div>
      <div class="stat-item maintenance-soon">
        <div class="stat-number">{{ statistics.maintenanceSoonCount }}</div>
        <div class="stat-label">即将维护</div>
      </div>
    </div>

    <!-- 设备列表 -->
    <div class="facility-table-container">
      <el-table
        :data="facilities"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        
        <el-table-column prop="facilityCode" label="设备编号" min-width="120" />
        
        <el-table-column prop="facilityName" label="设备名称" min-width="120" />
        
        <el-table-column prop="location" label="所在位置" min-width="150" />
        
        <el-table-column prop="facilityType" label="设备类型" min-width="100" />
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="responsiblePerson" label="负责人" min-width="100" />
        
        <el-table-column prop="nextMaintenanceDate" label="下次维护" min-width="120">
          <template #default="{ row }">
            <span v-if="row.nextMaintenanceDate" :class="getMaintenanceClass(row.daysToNextMaintenance)">
              {{ row.nextMaintenanceDate }}
              <span v-if="row.daysToNextMaintenance >= 0" class="days-info">
                ({{ row.daysToNextMaintenance }}天后)
              </span>
              <span v-else class="overdue-info">
                (逾期{{ Math.abs(row.daysToNextMaintenance) }}天)
              </span>
            </span>
            <span v-else class="no-data">未设置</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleViewDetails(row)">
                详情
              </el-button>
              <el-button 
                v-if="userStore.canManageFacilities"
                type="success" 
                size="small" 
                @click="handleEdit(row)">
                编辑
              </el-button>
              <el-dropdown 
                v-if="userStore.canManageFacilities"
                @command="(command) => handleMoreActions(command, row)">
                <el-button type="info" size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="maintenance">维护记录</el-dropdown-item>
                    <el-dropdown-item command="add-maintenance">添加维护</el-dropdown-item>
                    <el-dropdown-item 
                      v-if="userStore.hasAdminAccess" 
                      command="delete" 
                      divided>删除设备</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 设备详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      title="设备详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedFacility" class="facility-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备编号">{{ selectedFacility.facilityCode }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ selectedFacility.facilityName }}</el-descriptions-item>
          <el-descriptions-item label="所在位置">{{ selectedFacility.location }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ selectedFacility.facilityType || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="制造商">{{ selectedFacility.manufacturer || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="购买日期">{{ selectedFacility.purchaseDate || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="保修期限">{{ selectedFacility.warrantyPeriod ? selectedFacility.warrantyPeriod + '个月' : '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="是否在保">
            <el-tag :type="selectedFacility.inWarranty ? 'success' : 'danger'">
              {{ selectedFacility.inWarranty ? '在保' : '过保' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="设备状态">
            <el-tag :type="getStatusType(selectedFacility.status)">
              {{ getStatusText(selectedFacility.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{ selectedFacility.responsiblePerson || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedFacility.contactPhone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="维护周期">{{ selectedFacility.maintenanceCycle ? selectedFacility.maintenanceCycle + '天' : '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="上次维护">{{ selectedFacility.lastMaintenanceDate || '未维护' }}</el-descriptions-item>
          <el-descriptions-item label="下次维护">{{ selectedFacility.nextMaintenanceDate || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="设备描述" :span="2">{{ selectedFacility.description || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 新增/编辑设备对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editMode ? '编辑设备' : '新增设备'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="facilityFormRef"
        :model="facilityForm"
        :rules="facilityRules"
        label-width="100px"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="facilityCode">
              <el-input v-model="facilityForm.facilityCode" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="facilityName">
              <el-input v-model="facilityForm.facilityName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所在位置" prop="location">
              <el-input v-model="facilityForm.location" placeholder="请输入所在位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="facilityType">
              <el-input v-model="facilityForm.facilityType" placeholder="请输入设备类型" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="facilityForm.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="facilityForm.purchaseDate"
                type="date"
                placeholder="请选择购买日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="保修期限" prop="warrantyPeriod">
              <el-input-number
                v-model="facilityForm.warrantyPeriod"
                placeholder="月"
                style="width: 100%"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="facilityForm.status" placeholder="请选择设备状态" style="width: 100%">
                <el-option label="正常" :value="1" />
                <el-option label="维修中" :value="2" />
                <el-option label="报废" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input v-model="facilityForm.responsiblePerson" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="facilityForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="维护周期" prop="maintenanceCycle">
              <el-input-number
                v-model="facilityForm.maintenanceCycle"
                placeholder="天"
                style="width: 100%"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次维护" prop="lastMaintenanceDate">
              <el-date-picker
                v-model="facilityForm.lastMaintenanceDate"
                type="date"
                placeholder="请选择上次维护日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="设备描述" prop="description">
          <el-input
            v-model="facilityForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, ArrowDown } from '@element-plus/icons-vue'
import { 
  getFacilityPage, 
  getFacilityDetail, 
  addFacility, 
  updateFacility, 
  deleteFacility, 
  getStatistics 
} from '@/api/facility'
import { useUserStore } from '@/stores/user'

// 用户状态管理
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const showDetailsDialog = ref(false)
const showAddDialog = ref(false)
const editMode = ref(false)
const selectedFacility = ref(null)

// 表单引用
const facilityFormRef = ref()

// 数据
const facilities = ref([])
const statistics = reactive({
  totalCount: 0,
  normalCount: 0,
  maintainingCount: 0,
  scrappedCount: 0,
  maintenanceSoonCount: 0
})

// 表单数据
const facilityForm = reactive({
  id: null,
  facilityCode: '',
  facilityName: '',
  location: '',
  facilityType: '',
  manufacturer: '',
  purchaseDate: null,
  warrantyPeriod: null,
  status: 1,
  responsiblePerson: '',
  contactPhone: '',
  description: '',
  maintenanceCycle: null,
  lastMaintenanceDate: null
})

// 表单验证规则
const facilityRules = {
  facilityCode: [
    { required: true, message: '请输入设备编号', trigger: 'blur' }
  ],
  facilityName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入所在位置', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ],
  contactPhone: [
    { pattern: /^$|^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadFacilities()
}

const refreshData = () => {
  loadFacilities()
  loadStatistics()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadFacilities()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadFacilities()
}

const getStatusType = (status) => {
  const statusMap = {
    1: 'success', // 正常
    2: 'warning', // 维修中
    3: 'danger'   // 报废
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '正常',
    2: '维修中',
    3: '报废'
  }
  return statusMap[status] || '未知'
}

const getMaintenanceClass = (days) => {
  if (days < 0) return 'overdue'
  if (days <= 7) return 'urgent'
  if (days <= 30) return 'soon'
  return 'normal'
}

const handleViewDetails = (facility) => {
  selectedFacility.value = facility
  showDetailsDialog.value = true
}

const handleEdit = (facility) => {
  editMode.value = true
  Object.assign(facilityForm, facility)
  facilityForm.purchaseDate = facility.purchaseDate ? new Date(facility.purchaseDate) : null
  facilityForm.lastMaintenanceDate = facility.lastMaintenanceDate ? new Date(facility.lastMaintenanceDate) : null
  showAddDialog.value = true
}

const handleMoreActions = (command, facility) => {
  switch (command) {
    case 'maintenance':
      // 打开维护记录对话框
      break
    case 'add-maintenance':
      // 打开添加维护记录对话框
      break
    case 'delete':
      handleDelete(facility)
      break
  }
}

const handleDelete = async (facility) => {
  try {
    await ElMessageBox.confirm('确定要删除该设备吗？此操作不可恢复', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
    
    await deleteFacility(facility.id)
    ElMessage.success('设备删除成功')
    
    loadFacilities()
    loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

const handleSave = async () => {
  if (!facilityFormRef.value) return
  
  await facilityFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        const formData = {
          ...facilityForm,
          purchaseDate: facilityForm.purchaseDate ? facilityForm.purchaseDate.toISOString().split('T')[0] : null,
          lastMaintenanceDate: facilityForm.lastMaintenanceDate ? facilityForm.lastMaintenanceDate.toISOString().split('T')[0] : null
        }
        
        if (editMode.value) {
          await updateFacility(facilityForm.id, formData)
          ElMessage.success('设备信息更新成功')
        } else {
          await addFacility(formData)
          ElMessage.success('设备添加成功')
        }
        
        showAddDialog.value = false
        resetForm()
        loadFacilities()
        loadStatistics()
      } catch (error) {
        ElMessage.error(editMode.value ? '更新失败：' + (error.message || '未知错误') : '添加失败：' + (error.message || '未知错误'))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

const resetForm = () => {
  editMode.value = false
  Object.assign(facilityForm, {
    id: null,
    facilityCode: '',
    facilityName: '',
    location: '',
    facilityType: '',
    manufacturer: '',
    purchaseDate: null,
    warrantyPeriod: null,
    status: 1,
    responsiblePerson: '',
    contactPhone: '',
    description: '',
    maintenanceCycle: null,
    lastMaintenanceDate: null
  })
  if (facilityFormRef.value) {
    facilityFormRef.value.clearValidate()
  }
}

// 生成新的设备编号
const generateFacilityCode = () => {
  const now = new Date()
  const year = now.getFullYear().toString().slice(-2)
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 100)).padStart(2, '0')
  return `EQ-${year}${month}${day}${random}`
}

// 打开新增对话框时自动生成设备编号
const handleAddNew = () => {
  resetForm()
  facilityForm.facilityCode = generateFacilityCode()
  showAddDialog.value = true
}

// 数据加载方法
const loadFacilities = async () => {
  loading.value = true
  try {
    const response = await getFacilityPage({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value,
      status: statusFilter.value
    })
    
    if (response.data) {
      facilities.value = response.data.records || response.data.content || response.data
      total.value = response.data.total || response.data.totalElements || 0
    }
    
  } catch (error) {
    console.warn('API调用失败，使用模拟数据作为备用:', error)
    // 如果API调用失败，使用模拟数据作为备用
    facilities.value = generateMockFacilities()
    total.value = 50
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await getStatistics()
    
    if (response.data) {
      Object.assign(statistics, response.data)
    } else {
      // 如果没有数据，使用默认值
      Object.assign(statistics, {
        totalCount: 0,
        normalCount: 0,
        maintainingCount: 0,
        scrappedCount: 0,
        maintenanceSoonCount: 0
      })
    }
    
  } catch (error) {
    console.warn('统计数据API调用失败，使用模拟数据作为备用:', error)
    Object.assign(statistics, {
      totalCount: 25,
      normalCount: 20,
      maintainingCount: 3,
      scrappedCount: 2,
      maintenanceSoonCount: 5
    })
  }
}

// 生成模拟数据
const generateMockFacilities = () => {
  const facilityTypes = ['空调设备', '电梯设备', '安防设备', '给排水设备', '供电设备']
  const locations = ['1号楼', '2号楼', '3号楼', '地下室', '配电室', '大厅', '小区大门']
  const manufacturers = ['格力电器', '奥的斯电梯', '海康威视', '格兰富', '康明斯']
  const statuses = [1, 2, 3]
  
  return Array.from({ length: pageSize.value }, (_, index) => {
    const id = (currentPage.value - 1) * pageSize.value + index + 1
    const status = statuses[index % statuses.length]
    const nextMaintenanceDate = new Date(Date.now() + Math.random() * 90 * 24 * 60 * 60 * 1000)
    const daysToNextMaintenance = Math.floor((nextMaintenanceDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24))
    
    return {
      id,
      facilityCode: `EQ-${String(id).padStart(3, '0')}`,
      facilityName: `设备${id}`,
      location: locations[index % locations.length],
      facilityType: facilityTypes[index % facilityTypes.length],
      manufacturer: manufacturers[index % manufacturers.length],
      purchaseDate: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      warrantyPeriod: 24 + Math.floor(Math.random() * 36),
      status,
      statusDesc: status === 1 ? '正常' : status === 2 ? '维修中' : '报废',
      responsiblePerson: `负责人${id}`,
      contactPhone: `138${String(id).padStart(8, '0')}`,
      description: `设备${id}的详细描述`,
      maintenanceCycle: 30 + Math.floor(Math.random() * 60),
      lastMaintenanceDate: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      nextMaintenanceDate: nextMaintenanceDate.toISOString().split('T')[0],
      daysToNextMaintenance,
      inWarranty: Math.random() > 0.3
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadFacilities()
  loadStatistics()
})

// 监听对话框关闭事件
const handleDialogClose = () => {
  resetForm()
}
</script>

<style scoped>
.facility-management {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.management-header h2 {
  margin: 0;
  color: white;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.stats-row {
  display: flex;
  gap: 24px;
  padding: 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-item.normal {
  border-left: 4px solid #67c23a;
}

.stat-item.maintaining {
  border-left: 4px solid #e6a23c;
}

.stat-item.scrapped {
  border-left: 4px solid #f56c6c;
}

.stat-item.maintenance-soon {
  border-left: 4px solid #409eff;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.facility-table-container {
  padding: 24px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.no-data {
  color: #c0c4cc;
  font-style: italic;
}

.days-info {
  font-size: 12px;
  color: #909399;
}

.overdue-info {
  font-size: 12px;
  color: #f56c6c;
}

.urgent {
  color: #f56c6c;
  font-weight: bold;
}

.soon {
  color: #e6a23c;
}

.normal {
  color: #67c23a;
}

.overdue {
  color: #f56c6c;
  font-weight: bold;
}

.facility-details {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .management-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .stats-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
